// stores/usePaymentStore.ts
import { defineStore } from 'pinia'
import { paymentApi, type PaymentInfo, type PayOrderParams, PaymentStatus } from '@/api/payment'

interface PaymentState {
  currentPayment: PaymentInfo | null
  loading: boolean
  error: string | null
}

export const usePaymentStore = defineStore('payment', {
  state: (): PaymentState => ({
    currentPayment: null,
    loading: false,
    error: null,
  }),

  getters: {
    // 获取支付状态
    paymentStatus: (state) => {
      return state.currentPayment?.payment_status || PaymentStatus.Unpaid
    },

    // 检查是否已支付
    isPaid: (state) => {
      return state.currentPayment?.payment_status === PaymentStatus.Paid
    },
  },

  actions: {
    // 设置加载状态
    setLoading(loading: boolean) {
      this.loading = loading
    },

    // 设置错误信息
    setError(error: string | null) {
      this.error = error
    },

    // 获取支付信息
    async fetchPaymentInfo(orderId: number) {
      this.setLoading(true)
      this.setError(null)

      try {
        const info = await paymentApi.getPaymentInfo(orderId)
        this.currentPayment = info
        return info
      } catch (error: any) {
        console.error('获取支付信息失败:', error)
        this.setError(error.message || '获取支付信息失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },

    // 处理支付
    async payOrder(orderId: number, params: PayOrderParams) {
      this.setLoading(true)
      this.setError(null)

      try {
        const response = await paymentApi.payOrder(orderId, params)

        // 更新支付状态
        if (this.currentPayment) {
          this.currentPayment.payment_status = PaymentStatus.Paid
          this.currentPayment.payment_time = new Date().toISOString()
        }

        return response
      } catch (error: any) {
        console.error('支付失败:', error)
        this.setError(error.message || '支付失败')
        throw error
      } finally {
        this.setLoading(false)
      }
    },
  },
})
